package db

import (
	"fmt"
	"github.com/cn-ygf/go-admin/pkg/config"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
)

var (
	db    *gorm.DB
	err   error
	isDev bool
)

func Db() *gorm.DB {
	if isDev {
		return db.Debug()
	}
	return db
}

func Load() error {
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		config.GetString("mysql.user"),
		config.GetString("mysql.pass"),
		config.GetString("mysql.host"),
		config.GetInt("mysql.port"),
		config.GetString("mysql.db"),
	)
	db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			TablePrefix:   config.GetString("mysql.prefix"), // 表名前缀
			SingularTable: true,                             // 使用单数表名
			NameReplacer:  nil,
			NoLowerCase:   false,
		},
	})
	if err != nil {
		return err
	}
	isDev = config.GetBool("server.dev")
	return nil
}

func AutoMigrate(dst ...interface{}) error {
	return db.AutoMigrate(dst...)
}
